<?php
/**
 * 显示可视性良好地系统错误
 * 
 * @param string $msg 错误信息$1,$2...用来替换参数2中的文本
 * @param array $highlight 需要高亮的文本信息
 */
function sys_error($msg, $highlight = array())
{
	$search = array();
	if(!is_array($highlight))
	{
		$search[] = '{1}';
		$highlight = array($highlight);
	}
	else
	{
		$len = count($highlight);
		for($i = 1; $i <= $len; $i++)
		{
			$search[] = '{'.$i.'}';
		}
	}
	
	foreach($highlight as &$value)
	{
		$value= '<span style="color:red;">'.$value.'</span>';
	}
	
	$msg = str_replace($search, $highlight, $msg);
	
	header("Content-type: text/html; charset=utf-8");
	require(SYS.'/core/error_template.php');
	exit ;
}

/**
 * 获取当前页面URL
 */
function current_url()
{
    $protocol = 'http://';
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')
    {
        $protocol = 'https://';
    } 
    return $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
} 

/**
 * 获取网站URL
 */
function site_url()
{
    $protocol = 'http://';
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')
    {
        $protocol = 'https://';
    } 
    return trim($protocol . $_SERVER['HTTP_HOST'], '/');
} 

/**
 * URL跳转
 */
function redirect($url, $time = 0, $msg = '')
{ 
    // 多行URL地址支持
    $url = str_replace(array("\n", "\r"), '', $url);
    if (empty($msg))
        $msg = "系统将在{$time}秒之后自动跳转到{$url}！";
    if (!headers_sent())
    {
        if (0 === $time)
        {
            header("Location: " . $url);
        } 
        else
        {
            header("refresh:{$time};url={$url}");
            echo($msg);
        } 
        exit();
    } 
    else
    {
        $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
        if ($time != 0)
            $str .= $msg;
        exit($str);
    } 
} 

/**
 * 获取客户端IP地址
 * 
 * @return string $ip
 */
function get_client_ip()
{
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
    {
        $ip = getenv("HTTP_CLIENT_IP");
    } 
    else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
        $ip = getenv("REMOTE_ADDR");
    else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else
        $ip = "unknown";
    return ($ip);
} 

/**
 * 向主机发送post请求，并对字符串进行 urlencode 编码
 * 
 * @param string $ url 请求主机
 * @param string $ data post数据内容（格式：用key=value&key=value，或者关联数组）
 * @param string $ method 请求方式 get or post
 * @param string $ data type 请求的数据格式， var_export 或者 json 格式
 * @param int $ timeout 请求的超时设置
 * @return mixed 
 */
function get_url_contents($url, $data = '', $method = "get", $data_type = 'var_export', $timeout = 60)
{
    $ch = curl_init(); // Create curl resource			
    if ('get' == strtolower($method))
    {
        $url = is_array($data) ? $url . '?' . http_build_query($data) : $url . '?' . $data ;
        curl_setopt($ch, CURLOPT_URL, $url);
    } 
    else
    {
        $data = is_array($data) ? http_build_query($data) : $data ;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    } 

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout) ;
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the transfer as a string
    $output = curl_exec($ch);
    curl_close($ch);

    if ($data_type == 'var_export')
    {
        $result = '' ;
        @eval("\$result=$output;");
        return $result ;
    } elseif ('json' == $data_type)
    {
        return json_decode($output, true) ;
    } 
    else
    {
        return $output ;
    } 
} 

/**
 * 下载文件
 * 
 * @param string $filename 下载的文件名包含完整路径
 * @param integer $expire 下载内容浏览器缓存时间
 * @return void 
 */
function download ($filename, $expire = 180)
{
    $length = filesize($filename);
    if (!empty($filename))
    {
        $type = mime_content_type($filename);
    } 
    else
    {
        $type = "application/octet-stream";
    } 
    // 发送Http Header信息 开始下载
    header("Pragma: public");
    header("Cache-control: max-age=" . $expire); 
    // header('Cache-Control: no-store, no-cache, must-revalidate');
    header("Expires: " . gmdate("D, d M Y H:i:s", time() + $expire) . "GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . "GMT");
    header("Content-Disposition: attachment; filename=" . $filename);
    header("Content-Length: " . $length);
    header("Content-type: " . $type);
    header('Content-Encoding: none');
    header("Content-Transfer-Encoding: binary");

    exit();
}